"""
通知窗口 - 录音提示和讲话提示
"""
from PyQt6.QtWidgets import QWidget, QLabel, QVBoxLayout, QGraphicsOpacityEffect
from PyQt6.QtCore import Qt, QTimer, QPropertyAnimation, QEasingCurve, QPoint, QRect
from PyQt6.QtGui import QPainter, QColor, QFont, QPen


class RecordingOverlay(QWidget):
    """录音提示窗口 - 屏幕中央"""
    
    def __init__(self):
        super().__init__()
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint | 
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Tool
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(300, 150)
        
        self.init_ui()
        self.setup_animation()
    
    def init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 图标标签
        self.icon_label = QLabel("🎙️")
        icon_font = QFont()
        icon_font.setPointSize(48)
        self.icon_label.setFont(icon_font)
        self.icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.icon_label)
        
        # 文字标签
        self.text_label = QLabel("正在录音...")
        text_font = QFont()
        text_font.setPointSize(16)
        text_font.setBold(True)
        self.text_label.setFont(text_font)
        self.text_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.text_label.setStyleSheet("color: white;")
        layout.addWidget(self.text_label)
        
        self.setLayout(layout)
    
    def paintEvent(self, event):
        """绘制圆角半透明背景"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 绘制背景
        painter.setBrush(QColor(0, 0, 0, 180))
        painter.setPen(QPen(QColor(255, 255, 255, 100), 2))
        painter.drawRoundedRect(self.rect(), 20, 20)
    
    def setup_animation(self):
        """设置动画"""
        self.opacity_effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.opacity_effect)
        
        self.fade_in_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.fade_in_animation.setDuration(200)
        self.fade_in_animation.setStartValue(0)
        self.fade_in_animation.setEndValue(1)
        self.fade_in_animation.setEasingCurve(QEasingCurve.Type.InOutCubic)
        
        self.fade_out_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.fade_out_animation.setDuration(200)
        self.fade_out_animation.setStartValue(1)
        self.fade_out_animation.setEndValue(0)
        self.fade_out_animation.setEasingCurve(QEasingCurve.Type.InOutCubic)
        self.fade_out_animation.finished.connect(self.hide)
    
    def show_overlay(self):
        """显示录音提示"""
        print("[RecordingOverlay] 显示录音提示")
        
        # 停止所有动画
        if self.fade_out_animation.state() == QPropertyAnimation.State.Running:
            self.fade_out_animation.stop()
        if self.fade_in_animation.state() == QPropertyAnimation.State.Running:
            self.fade_in_animation.stop()
        
        # 重置透明度
        self.opacity_effect.setOpacity(1.0)
        
        # 居中显示
        screen = self.screen().geometry()
        x = (screen.width() - self.width()) // 2
        y = (screen.height() - self.height()) // 2
        self.move(x, y)
        
        self.show()
        self.raise_()  # 确保窗口在最前面
        self.activateWindow()
    
    def hide_overlay(self):
        """隐藏录音提示"""
        print("[RecordingOverlay] 隐藏录音提示")
        
        if not self.isVisible():
            print("[RecordingOverlay] 窗口已经隐藏，跳过")
            return
        
        # 立即隐藏，不用动画（更可靠）
        self.hide()
        
        # 确保后续也不会再显示
        QTimer.singleShot(100, lambda: self.hide() if self.isVisible() else None)


class SpeakingNotification(QWidget):
    """讲话通知窗口 - 右下角"""
    
    def __init__(self):
        super().__init__()
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint | 
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Tool
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(280, 100)
        
        self.auto_hide_timer = QTimer()
        self.auto_hide_timer.timeout.connect(self.hide_notification)
        
        self.init_ui()
        self.setup_animation()
    
    def init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 用户名标签
        self.user_label = QLabel("👤 用户")
        user_font = QFont()
        user_font.setPointSize(14)
        user_font.setBold(True)
        self.user_label.setFont(user_font)
        self.user_label.setStyleSheet("color: white;")
        layout.addWidget(self.user_label)
        
        # 状态标签
        self.status_label = QLabel("正在讲话...")
        status_font = QFont()
        status_font.setPointSize(11)
        self.status_label.setFont(status_font)
        self.status_label.setStyleSheet("color: #aaaaaa;")
        layout.addWidget(self.status_label)
        
        self.setLayout(layout)
    
    def paintEvent(self, event):
        """绘制圆角半透明背景"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 绘制背景（带渐变效果）
        painter.setBrush(QColor(40, 40, 40, 220))
        painter.setPen(QPen(QColor(100, 150, 255, 150), 2))
        painter.drawRoundedRect(self.rect(), 15, 15)
    
    def setup_animation(self):
        """设置动画"""
        self.opacity_effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.opacity_effect)
        
        # 淡入动画
        self.fade_in_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.fade_in_animation.setDuration(300)
        self.fade_in_animation.setStartValue(0)
        self.fade_in_animation.setEndValue(1)
        self.fade_in_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
        
        # 淡出动画
        self.fade_out_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.fade_out_animation.setDuration(300)
        self.fade_out_animation.setStartValue(1)
        self.fade_out_animation.setEndValue(0)
        self.fade_out_animation.setEasingCurve(QEasingCurve.Type.InCubic)
        self.fade_out_animation.finished.connect(self.hide)
        
        # 滑入动画
        self.slide_animation = QPropertyAnimation(self, b"pos")
        self.slide_animation.setDuration(300)
        self.slide_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
    
    def show_notification(self, user_name: str):
        """显示讲话通知"""
        self.user_label.setText(f"👤 {user_name}")
        
        # 停止自动隐藏计时器
        self.auto_hide_timer.stop()
        
        # 计算右下角位置
        screen = self.screen().geometry()
        end_x = screen.width() - self.width() - 20
        end_y = screen.height() - self.height() - 60
        
        # 从右侧滑入
        start_x = screen.width()
        start_y = end_y
        
        self.move(start_x, start_y)
        self.show()
        
        # 执行滑入和淡入动画
        self.slide_animation.setStartValue(QPoint(start_x, start_y))
        self.slide_animation.setEndValue(QPoint(end_x, end_y))
        self.slide_animation.start()
        self.fade_in_animation.start()
    
    def hide_notification(self):
        """隐藏讲话通知"""
        self.fade_out_animation.start()
    
    def set_auto_hide(self, delay_ms: int = 3000):
        """设置自动隐藏"""
        self.auto_hide_timer.start(delay_ms)


class WaveformWidget(QWidget):
    """音频波形动画组件（可选增强）"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(200, 60)
        self.wave_offset = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_wave)
    
    def start_animation(self):
        """启动波形动画"""
        self.timer.start(50)  # 20fps
    
    def stop_animation(self):
        """停止波形动画"""
        self.timer.stop()
        self.update()
    
    def update_wave(self):
        """更新波形"""
        self.wave_offset = (self.wave_offset + 5) % 360
        self.update()
    
    def paintEvent(self, event):
        """绘制波形"""
        import math
        
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        painter.setPen(QPen(QColor(100, 200, 255), 2))
        
        # 绘制正弦波
        points = []
        for x in range(self.width()):
            angle = (x + self.wave_offset) * 2
            y = self.height() // 2 + int(20 * math.sin(math.radians(angle)))
            points.append(QPoint(x, y))
        
        for i in range(len(points) - 1):
            painter.drawLine(points[i], points[i + 1])

